#!/bin/bash
# feature: ubuntu /etc/apt/sources.list change to aliyun
# usage:bash <(curl -s http://…….sh)

# look os CODENAME
CODENAME=$(lsb_release -c | awk '{print $2}')

# test aliyun webdir whether exist for spec CODENAME
URL_ALIYUN_CODENAME="http://mirrors.aliyun.com/ubuntu/dists/"$CODENAME"/"

if curl -f ${URL_ALIYUN_CODENAME} >/dev/null 2>&1; then

  SOURCE_FILE="/etc/apt/sources.list"

  # protect the exist bak file
  source_back_up_file=$SOURCE_FILE".bak"
  while [ -e $source_back_up_file ]; do
    source_back_up_file=$source_back_up_file".bak"
  done

  sudo mv ${SOURCE_FILE} ${source_back_up_file}

  cat <<EOF | sudo tee ${SOURCE_FILE}
deb http://mirrors.aliyun.com/ubuntu/ $CODENAME main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ $CODENAME-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ $CODENAME-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ $CODENAME-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ $CODENAME-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ $CODENAME main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ $CODENAME-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ $CODENAME-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ $CODENAME-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ $CODENAME-backports main restricted universe multiverse
EOF

  sudo apt-get update

  echo "over"
else
  echo "aliyun not support codename${CODENAME} "
  exit 0
fi